package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

//// 定义一对多的结构体
//type User struct {
//	gorm.Model
//	// 该字段不会再数据库中真正创建
//	CreditCards []*CreditCard
//}
//
//type CreditCard struct {
//	gorm.Model
//	Number string
//	UserID uint // 外键，
//}

type User struct {
	gorm.Model
	MemberNumber string       `gorm:"index"`
	CreditCards  []CreditCard `gorm:"foreignKey:UserNumber;references:MemberNumber"`
}

type CreditCard struct {
	gorm.Model
	Number     string
	UserNumber string `gorm:"index"`
}

func main() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	// 1. 定义数据库的地址
	// charset 字符编码类型
	// parseTime 时间格式
	// loc 时间分区
	dsn := "root:jxkj@123@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}
	fmt.Println(db)

	// 2. 自动创建表
	db.AutoMigrate(User{}, CreditCard{})

	// 3. 插入数据
	//user := &User{
	//	MemberNumber: "123456",
	//	CreditCards: []CreditCard{
	//		{Number: "123456"},
	//		{Number: "654321"},
	//	},
	//}
	//db.Create(user)

	// 4. 查询数据
	user1 := &User{}
	db.Where("member_number = ?", "123456").First(user1)
	fmt.Println(user1)

	// 关联查询 CreditCard
	db.Model(user1).Association("CreditCards").Find(&user1.CreditCards)
	fmt.Println(user1.CreditCards)

	// preload 关联查询
	user2 := &User{}
	db.Preload("CreditCards").Where("member_number = ?", "123456").First(user2)
	fmt.Println(user2)
}
